package com.study.talk.module.netty.handler;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.study.talk.common.util.RedisUtils;
import com.study.talk.module.entity.User;
import com.study.talk.module.netty.message.request.SmsSendRequest;
import com.study.talk.module.netty.message.response.SmsSendResponse;
import com.study.talk.module.service.MessageService;
import com.study.talk.module.service.UserService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@ChannelHandler.Sharable
@Component
@Slf4j
public class SmsSendHandler extends SimpleChannelInboundHandler<SmsSendRequest> {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private MessageService messageService;


    @Resource
    private UserService userService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SmsSendRequest smsSendRequest) throws Exception {
        if (userService.getOne(new QueryWrapper<User>().eq("username",smsSendRequest.getUsername())) == null){

            if (userService.getOne(new QueryWrapper<User>().eq("phone_number",smsSendRequest.getPhoneNumber())) == null){
                String code = generatedCode(4);
                SendSmsResponse smsResponse = messageService.sendSms(smsSendRequest.getPhoneNumber(), code);
                if (smsResponse.body.code.equals("OK")){
                    redisUtils.set(smsSendRequest.getPhoneNumber(), code, 60, TimeUnit.SECONDS);
                    SmsSendResponse response = new SmsSendResponse("OK",code, smsSendRequest.getPhoneNumber(),smsSendRequest.getUsername(),"成功");
                    ctx.channel().writeAndFlush(response);
                }else {
                    SmsSendResponse response = new SmsSendResponse("FAIL",null,null,null,"短信发送失败:"+smsResponse.body.message);
                    ctx.channel().writeAndFlush(response);
                }
            }else {
                SmsSendResponse response = new SmsSendResponse("FAIL",null,null,null,"手机号已被注册");
                ctx.channel().writeAndFlush(response);
            }

        }else {
            SmsSendResponse response = new SmsSendResponse("FAIL",null,null,null,"用户名已经存在");
            ctx.channel().writeAndFlush(response);
        }
    }


    public static String generatedCode(int count) {
        return String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, count - 1)));
    }
}
